package com.yoke.controller.order;

/**
 * Created by jiangzeyin on 2017/5/15.
 */

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yoke.common.JsonMessage;
import com.yoke.common.base.NginxBaseControl;
import com.yoke.service.order.OrderService;
import com.yoke.util.FileUtil;
import com.yoke.util.JsonUtil;
import com.yoke.util.StringUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * Created by jiangzeyin on 2017/5/15.
 */
@Controller
@RequestMapping("order")
public class EditKhControl extends NginxBaseControl {

    @Resource
    OrderService orderService;

    @RequestMapping(value = "add.html", produces = MediaType.TEXT_HTML_VALUE)
    public String index() {
        return "order/add_kh";
    }

    /**
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "edit.html", produces = MediaType.TEXT_HTML_VALUE)
    public String edit(String id) throws Exception {
        String filePath = orderService.getCustomerInfoFile().getPath();// getOrderUserConfFile();
        id = StringUtil.convertNULL(id);
        JSONArray jsonArray = (JSONArray) JsonUtil.readJson(filePath);
        for (int i = jsonArray.size() - 1; i >= 0; i--) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String id_ = jsonObject.getString("id");
            if (id.equals(id_)) {
                request.setAttribute("item", jsonObject);
                return "order/add_kh";
            }
        }
        return "order/add_kh";
    }

    /**
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "del_{id}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String del_(@PathVariable String id) throws Exception {
        id = StringUtil.convertNULL(id);
        String filePath = orderService.getCustomerInfoFile().getPath();
        JSONArray jsonArray = (JSONArray) JsonUtil.readJson(filePath);
        Iterator<Object> iterable = jsonArray.iterator();
        int count = jsonArray.size();
        while (iterable.hasNext()) {
            JSONObject jsonObject = (JSONObject) iterable.next();
            String parent = jsonObject.getString("parent");
            if (!userName.equals(parent))
                continue;
            String id_ = jsonObject.getString("id");
            if (id.equals(id_)) {
                iterable.remove();
                break;
            }
        }
        if (count == jsonArray.size())
            return JsonMessage.getString(400, "删除失败");
        String newsJson = JsonUtil.formatJson(jsonArray.toString());
        FileUtil.writeFile(filePath, newsJson);
        return JsonMessage.getString(200, "删除成功");

    }


    @RequestMapping(value = "save_kh.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String save_kh(String id, String pwd, String mark) throws Exception {
        String filePath = orderService.getCustomerInfoFile().getPath();
        JSONArray jsonArray = (JSONArray) JsonUtil.readJson(filePath);
        Iterator<Object> iterable = jsonArray.iterator();
        String newPwd = null;
        if (!StringUtil.IsEmpty(pwd)) {
            if (StringUtil.IsEmpty(pwd, 6, 20))
                return JsonMessage.getString(400, "请输入6-20的位的密码");
            else
                newPwd = pwd;
        }
        while (iterable.hasNext()) {
            JSONObject jsonObject = (JSONObject) iterable.next();
            String parent = jsonObject.getString("parent");
            if (!userName.equals(parent))
                continue;
            String id_ = jsonObject.getString("id");
            if (id.equals(id_)) {
                jsonObject.put("mark", mark);
                if (newPwd != null)
                    jsonObject.put("pwd", newPwd);
                break;
            }
        }
        String newsJson = JsonUtil.formatJson(jsonArray.toString());
        FileUtil.writeFile(filePath, newsJson);
        return JsonMessage.getString(200, "修改成功");
    }

    @RequestMapping(value = "add_kh.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String add_kh(String name, String pwd, String mark) throws Exception {
        if (StringUtil.IsEmpty(name, 4, 20))
            return JsonMessage.getString(400, "请输入4-20的登录名");
        if (!Pattern.matches("^[0-9a-zA-Z_]+$", name))
            return JsonMessage.getString(400, "客户名只能是数字,字母或者 '_'");
        if (StringUtil.IsEmpty(pwd, 6, 20))
            return JsonMessage.getString(400, "请输入6-20的位的密码");
        String filePath = orderService.getCustomerInfoFile().getPath();
        JSONArray jsonArray = (JSONArray) JsonUtil.readJson(filePath);
        for (int i = jsonArray.size() - 1; i >= 0; i--) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String userName = jsonObject.getString("name");
            if (name.equalsIgnoreCase(userName)) {
                return JsonMessage.getString(400, "已经存在相同的登录名");
            }
        }
        // 过滤-
        name = name.replace('-', '_');
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", name);
        jsonObject.put("pwd", pwd);
        jsonObject.put("mark", mark);
        jsonObject.put("parent", userName);
        jsonObject.put("id", UUID.randomUUID());
        jsonArray.add(jsonObject);
        String newsJson = JsonUtil.formatJson(jsonArray.toString());
        FileUtil.writeFile(filePath, newsJson);
        return JsonMessage.getString(200, "添加成功");
    }


}
